package com.wan.core.timer.bucket;

import com.wan.core.timer.TimerWheel;
import com.wan.core.timer.task.TaskNode;

/**
 * @author wwh
 * @date 2022/6/28 11:46
 */
public class TimeBuckets {
    /** 当前桶索引 */
    private int bucketIndex;
    /** 桶数组 */
    private final Bucket[] buckets;

    public TimeBuckets(TimerWheel timerWheel,int size, int current) {
        buckets = new Bucket[size];
        for (int i = 0; i < size; i++) {
            buckets[i] = new Bucket(i,timerWheel);
        }
        this.bucketIndex = current;
    }

    /**
     * 添加任务到指定槽位
     * @param index 索引槽位
     * @param taskNode 任务
     */
    public void addTask(int index,TaskNode taskNode){
        Bucket bucket = buckets[index];
        taskNode.setBucket(bucket);
        //过期直接执行
        if(taskNode.isExpired()){
            taskNode.execute();
            return;
        }
        bucket.add(taskNode);
    }

    /**
     * 时间轮转动（槽位索引 +1）
     * ->单线程驱动，避免多线程竞争
     * @return 是否满轮（索引回到0）
     */
    public boolean turn(){
        bucketIndex++;
        boolean flowOver = false;
        if(bucketIndex >= buckets.length){
            bucketIndex = 0;
            flowOver = true;
        }
        buckets[bucketIndex].trigger();
        return flowOver;
    }




}
